import * as userService from '../services/userService';

export default {
  namespace: 'users',
  state: {
    list: [],
    total: null,
    page: null,
  },
  reducers: {
    load(state, {payload: {list, total, page}}) {
      console.log("load data");
      return {...state, list, total, page};
    },
    edit(state, {payload: record}) {
      console.log("reducers edit data");
      return {...state, editFlag: true, editRecord: record};
    },
    editFinish(state) {
      console.log("reducers editFinish data");
      return {...state, editFlag: false, editRecord: {}};
    }
  },
  effects: {
    * fetch({payload: {page = 1}}, {call, put}) {
      const {data, headers} = yield call(userService.fetch, {page});
      yield put({
        type: 'load',
        payload: {
          list: data,
          total: parseInt(headers['x-total-count'], 10),
          page: parseInt(page, 10),
        },
      });
    },
    * del({payload: id}, {call, put, select}) {
      yield call(userService.remove, {id});
      const page = yield select(state => state.users.page);
      yield put({type: "fetch", payload: {page}});
    },
    * update({payload: record}, {call, put, select}) {
      yield call(userService.update, {record});
      const page = yield select(state => state.users.page);
      yield put({type: "fetch", payload: {page}});
    }
  },
  subscriptions: {
    setup({dispatch, history}) {
      return history.listen(({pathname, query}) => {
        if (pathname === '/users') {
          dispatch({type: 'fetch', payload: query});
        }
      });
    },
  },
};
